// 时间戳转化成YMD格式
export const dateFormat = (timestamp, formats) => {
  // formats格式包括
  // 1. Y-m-d
  // 2. Y-m-d H:i:s
  // 3. Y年m月d日
  // 4. Y年m月d日 H时i分
  formats = formats || 'Y-m-d';
  const zero = function(value) {
    if (value < 10) {
      return '0' + value;
    }
    return value;
  };
  const myDate = timestamp ? new Date(timestamp) : new Date();
  const year = myDate.getFullYear();
  const month = zero(myDate.getMonth() + 1);
  const day = zero(myDate.getDate());
  const hour = zero(myDate.getHours());
  const minite = zero(myDate.getMinutes());
  const second = zero(myDate.getSeconds());

  return formats.replace(/Y|m|d|H|i|s/ig, function(matches) {
    return ({
      Y: year,
      m: month,
      d: day,
      H: hour,
      i: minite,
      s: second
    })[matches];
  });
};

// Y-m-d H:i:s 截取
export const xFormat = (str) => {
  const reg1 = /^(\d{4})-(\d{2})-(\d{2})$/;
  const reg2 = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/;
  const reg3 = /^(\d{4})-(\d{1,2})月$/;
  const reg4 = /^(\d{4})-(\d{2})$/;
  const reg5 = /^(\d{1}):(\d{2})$/;
  const reg6 = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;
  if (reg1.test(str)) {
    const arr = str.split('-');
    return arr[1] + '-' + arr[2];
  }
  if (reg2.test(str)) {
    const arr = str.split(' ');
    return arr[1];
  }
  if (reg3.test(str)) {
    const arr = str.split('-');
    return arr[1];
  }
  if (reg4.test(str)) {
    const arr = str.split('-');
    return arr[1] + '月';
  }
  if (reg5.test(str)) {
    return '0' + str;
  }
  if (reg6.test(str)) {
    const arr = str.split(' ');
    const time = arr[1].split(':');
    return time[0] + ':' + time[1];
  }
  return str;
};
